import logging
import os
import asyncio
import subprocess
from datetime import datetime, timedelta
from asyncua import Client, ua

# 设置日志
# 设置日志格式，包括时间戳
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.basicConfig(level=logging.WARNING)
_logger = logging.getLogger('asyncua')

# 配置参数
reconnect_delay = 30  # 重新连接的延迟时间（秒）
disconnect_timeout = timedelta(minutes=3)  # 断开连接的超时时间
# disconnect_timeout = timedelta(seconds=10)  # 断开连接的超时时间
opcua_server_url = "opc.tcp://172.16.14.99:4840/freeopcua/server/"
# opcua_server_url = "opc.tcp://localhost:4840/freeopcua/server/"
if os.name == 'posix':  # 如果是类Unix系统，例如Linux
    opcua_server_url = "opc.tcp://127.0.0.1:4840/freeopcua/server/"
else:  # 其他操作系统，例如Windows
    opcua_server_url = "opc.tcp://172.16.14.99:4840/freeopcua/server/"
    pass

async def execute_bash_command():
    """
    执行bash命令以重启服务。
    """
    global last_connection_time
    last_connection_time = datetime.now()  # 重置最后连接时间
    _logger.warning("连接超时，执行bash命令重启服务")
    subprocess.run(["bash", "-c", "sudo supervisorctl restart svc"], check=False)


async def main():
    global last_connection_time
    last_connection_time = datetime.now()  # 最后连接时间
    while True:
        try:
            # 尝试连接到OPC UA服务器
            async with Client(url=opcua_server_url) as client:
                _logger.warning("已连接到OPC UA服务器")
                last_connection_time = datetime.now()  # 重置最后连接时间

                while True:
                    _logger.info("OPC UA 通讯正常")

                    await asyncio.sleep(30)
                    await client.check_connection()

        except Exception as e:  # 捕获所有异常
            now = datetime.now()
            print(now - last_connection_time)
            print(disconnect_timeout)
            if now - last_connection_time > disconnect_timeout:
                # 超时后执行bash命令
                await execute_bash_command()
            else:
                _logger.warning("OPC UA 发生错误,尝试连接中")
                await asyncio.sleep(reconnect_delay)  # 等待一段时间后重连


if __name__ == "__main__":
    asyncio.run(main())
